<template>
  <div id="addOrEditPage">
    <h2 class="title">{{ id ? "修改应用信息" : "创建应用" }}</h2>

    <div id="addOrEditFormWrapper">
      <el-form :model="form" label-width="80px" class="formLoading">
        <el-form-item label="应用 id" prop="id" v-if="id">
          <el-input :value="form.id" clearable disabled />
        </el-form-item>
        <el-form-item label="应用名称" prop="id">
          <el-input v-model="form.appName" clearable placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用描述" prop="appDesc">
          <el-input v-model="form.appDesc" clearable placeholder="请输入应用描述" />
        </el-form-item>
        <el-form-item label="应用图标" prop="appIcon">
          <PictureUploader v-model:image-url="form.appIcon" :file-upload-type="FileUploadTypeEnum.APP_ICON" />
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <el-select v-model="form.appType" placeholder="请选择应用类型">
              <el-option :value="AppTypeEnum.QUESTION" :label="AppTypeEnumMap.QUESTION" />
              <el-option :value="AppTypeEnum.SCORE" :label="AppTypeEnumMap.SCORE" />
          </el-select>
        </el-form-item>
        <el-form-item label="评分策略" prop="scoringStrategy">
          <el-select v-model="form.scoringStrategy" placeholder="请选择评分策略">
            <el-option :value="ScoringStrategyEnum.CUSTOMIZED" :label="ScoringStrategyEnumMap.CUSTOMIZED" />
            <!-- 评分与 AI 不能共存 -->
            <el-option :value="ScoringStrategyEnum.AI" :label="ScoringStrategyEnumMap.AI" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div id="buttonWrapper">
      <el-button class="submitButton" type="info" plain size="default" @click="router.back">返回</el-button>
      <el-button class="submitButton" type="primary" size="default" @click="doSubmit" :loading>提交</el-button>
      <el-button class="submitButton" type="info" plain size="default" :disabled="toQuestionPageButtonDisabled"
        @click="doGoToQuestionPage">
        {{ id ? "前往修改题目" : "前往添加题目" }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addAppUsingPost, editAppUsingPost, getAppVoByIdUsingGet, listAppByPageUsingPost } from '@/api/appController';
import PictureUploader from '@/components/PictureUploader.vue';
import { AppTypeEnum, AppTypeEnumMap, FileUploadTypeEnum, ResponseCodeEnum, ScoringStrategyEnum, ScoringStrategyEnumMap } from '@/enums';
import { ElLoading, ElMessage } from 'element-plus';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';


// 尝试读取传入的 id (保持响应式)
const { id } = defineProps(["id"])

// 路由
const router = useRouter()

// 表单默认信息 (此处分开放, 避免在编辑时点击创建应用, 数据不清空的问题)
const defaultFormData = {
  id: undefined,
  appName: '',
  appDesc: '',
  appIcon: '',
  appType: AppTypeEnum.QUESTION,
  scoringStrategy: ScoringStrategyEnum.CUSTOMIZED
}

// 表单查询请求数据
const form = ref<API.AppEditRequest>(defaultFormData);

// 提交按钮是否加载中
const loading = ref(false);

// 前往问题页面按钮是否可用
const toQuestionPageButtonDisabled = ref(true);

// 监听路由 $route 变化, 以区分编辑 App 和 修改 App, onMounted 做不到
watch(() => router.currentRoute.value.path, async (toPath) => {
  if (toPath === "/app/add") {
    form.value = defaultFormData;

    // 前往问题页面按钮设置为不可用 
    toQuestionPageButtonDisabled.value = true;
  } else {
    // 为表单添加加载效果
    const formLoading = ElLoading.service({
      // target 用 css 选择器即可
      target: "#addOrEditFormWrapper .formLoading",
      lock: true,
      text: "加载中...",
    });

    // 获取应用信息
    const result = await getAppVoByIdUsingGet({ id })

    // 赋值给表单
    if (result.data.code === ResponseCodeEnum.SUCCESS && result.data.data) {
      form.value = result.data.data;
    } else {
      ElMessage.error("获取应用数据失败: " + result.data.message);
    }

    // 前往问题页面按钮设置为可用 
    toQuestionPageButtonDisabled.value = false;

    formLoading.close();
  }
}, { immediate: true, deep: true })

// 新建应用 id
const newAppId = ref<string | undefined>(undefined);

/**
 * 提交表单
 */
const doSubmit = async () => {
  loading.value = true;

  // id 有值, 则为编辑, 否则为新增
  let result;
  if (form.value.id !== undefined) {
    result = await editAppUsingPost(form.value);
  } else {
    result = await addAppUsingPost(form.value);
  }

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    if (form.value.id === undefined) {
      ElMessage.success(`新建应用成功, 应用 id: ${result.data.data}`)
      newAppId.value = String(result.data.data);
    } else {
      ElMessage.success(`修改应用成功, 应用 id: ${form.value.id}`)
      ElMessage.warning("注: 应用修改后会重新变为 \"审核中\" 状态")
    }
    toQuestionPageButtonDisabled.value = false;
  } else {
    ElMessage.error("操作失败: " + result.data.message);
  }

  loading.value = false;
}

/**
 * 前往添加或编辑题目页面
 */
const doGoToQuestionPage = () => {
  router.push({
    name: '编辑题目',
    params: {
      appId: newAppId.value ?? id
    }
  })
}
</script>

<style scoped lang="less">
#addOrEditPage {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .title {
    font-size: 2.5em;
    margin: 50px 0;
  }
}

#addOrEditFormWrapper {
  width: 40%;
}

.submitButton {
  margin-top: 10px;
  width: 150px;
}
</style>